<?php

namespace App\service\nft;

use Exception;
use support\Log;
use support\Redis;
use think\facade\Db;
use crmeb\exceptions\AdminException;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

class NftServices
{
    /**
     * 添加nft
     * @param int $userId 要添加的用户id
     * @param int $id 藏品id
     * @param array $userInfo 要添加的用户信息
     * @param array $goodsInfo 藏品信息
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addNft(int $userId, int $id, array $userInfo, array $goodsInfo)
    {
        $prefix = env('REDIS_PREFIX');
//        $ttl_seconds = env('REDIS_TTL_SECONDS');

        // 编号 key
        $value_key = $prefix . 'goods_' . $id . '_number';

        // 开始 创建 合成藏品
        $findWhere = [];
        $findWhere[] = ['uid', '=', $userId];
        $findWhere[] = ['goods_id', '=', $id];

        $find = Db::name('nft')->where($findWhere)->find();

        //开始事务
        Db::startTrans();

        try {
            if (!$find) {
                /** @var NftServices $res */
                $nft_pk_id = Db::name('nft')->insertGetId([
                    'uid' => $userId,
                    'mobile' => $userInfo['mobile'],
                    'account_id' => $userInfo['account_id'],
                    'goods_id' => $goodsInfo['id'],
                    'goods_name' => $goodsInfo['name'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            } else {
                $nft_pk_id = $find['id'];
                Db::name('nft')->where('id', $find['id'])->update(['updated_at' => date('Y-m-d H:i:s')]);
            }

            $value = Redis::incrBy($value_key, 1);

            // 开始创建nft_list记录
            if (!Db::name('nft_list')->insert([
                'nft_pk_id' => $nft_pk_id,
                'uid' => $userId,
                'goods_id' => $id,
                'name' => $goodsInfo['name'],
                'value' => $value,
                'pic' => $goodsInfo['pic'],
                'hash' => $goodsInfo['pic_hash'],
                'prev_get_drop_time' => date('Y-m-d H:i:s'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ])) {
                throw new AdminException("网络错误请稍后重试3！");
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Redis::decrBy($value_key, 1);
            throw new AdminException($e->getMessage());
        }

        return true;
    }
}
